package com.benmei.weike.service;

import com.benmei.weike.paypal.GetAccessToken;
import com.benmei.weike.paypal.GetPaymentDetail;
import com.benmei.weike.util.JsonUtil;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;

public class PaymentByPaypalService {
//    @Value("${Paypal.Client_ID}")
//    public static String paypalAppId;
//    @Value("${Paypal.Secret_Key}")
//    public static String paypalSecretKey;

    private static String paypalAppId="ATVYLmKykLW5csoSU-1pCv6hCo9hhPm6WdDNQUANCg0SeCMN5mjajpp5CbkBU6Ro3QMpDmhO3RKDf6yP";
    private static String paypalSecretKey="EMokHKV6XuScWTsQcFPvLbzxCPjdbE5OBosDs8QS6Y5K7G-ce0m6rUN9jMeMhYFihcYxc0zC6-WX4-7E";

    private static Logger logger = LoggerFactory.getLogger(PaymentByPaypalService.class);

    public static void main(String[] args) {
        try {
            // Authorization Code and Co-relationID retrieved from Mobile SDK.
            String authorizationCode = "C101.Rya9US0s60jg-hOTMNFRTjDfbePYv3W_YjDJ49BVI6YJY80HvjL1C6apK8h3IIas.ZWOGll_Ju62T9SXRSRFHZVwZESK";
            String orderId = "PAY-77S07578D7632515RLLI2NDQ";
            String url = "https://api.sandbox.paypal.com/v1/payments/payment/";
            String get_url = "https://api.sandbox.paypal.com/v1/oauth2/token";
            String authHttp = httpPostMethod(get_url).toString();
//            GetAccessToken getAccessToken = JsonUtil.toObject(authHttp,GetAccessToken.class);
//            String response = sendGet(new StringBuilder(url).append(orderId).toString(),getAccessToken.getAccess_token());
//            GetPaymentDetail getPaymentDetail = JsonUtil.toObject(response,GetPaymentDetail.class);
//            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取token
     * @param uri
     * @return
     */
    public static String httpPostMethod(String uri) {
        String body = "";
       //创建客户端访问服务器的httpclient对象   打开浏览器
        HttpClient httpclient = new DefaultHttpClient();
        //2.以请求的连接地址创建get请求对象     浏览器中输入网址
        HttpPost httpPost = new HttpPost(uri);
        InputStream input;
        logger.info("执行请求： " + httpPost.getURI());
        try {
            // Execute the method.
            System.out.println(new StringBuffer(paypalAppId).append(" : ").append(paypalSecretKey).toString());
            String encoding = DatatypeConverter.printBase64Binary(new StringBuffer(paypalAppId).append(":").append(paypalSecretKey).toString().getBytes("UTF-8"));
            httpPost.setHeader("Authorization", "Basic " +encoding);

            List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
            pairList.add(new BasicNameValuePair("grant_type", "client_credentials"));
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
            //向服务器端发送请求 并且获取响应对象  浏览器中输入网址点击回车
            HttpResponse response = httpclient.execute(httpPost);
            StatusLine statusLine = (StatusLine) response.getStatusLine();//获取请求对象中的响应行对象
            int statusCode = statusLine.getStatusCode();//从状态行中获取状态码
            logger.info("状态码：" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + response.getStatusLine());
            }
            // Use caution: ensure correct character encoding and is not binary data
            //5.  可以接收和发送消息
            HttpEntity entity = response.getEntity();
            //6.从消息载体对象中获取操作的读取流对象
            input = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(input));
            String str1 = br.readLine();
            String result = new String(str1.getBytes("gbk"), "utf-8");
            body = result;
            System.out.println("服务器的响应是:" + result);
            br.close();
            input.close();
            httpPost.releaseConnection();
            logger.info(new String(response.getStatusLine().toString()));
        } catch (HttpException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return body;
    }

    /**
     * 获取支付结果
     * @param uri
     * @param access_token
     * @return
     */
    public static String sendGet(String uri,String access_token) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = uri;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Authorization","Bearer "+access_token);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
